<?php

namespace frontend\models;

use Yii;

/**
 * This is the model class for table "shop_order".
 *
 * @property string $orderId
 * @property integer $userId
 * @property string $addressId
 * @property string $amount
 * @property integer $status
 * @property integer $expressId
 * @property string $expressno
 * @property string $createtime
 * @property string $updatetime
 *
 * @property OrderDetail[] $orderDetails
 * @property Address $address
 * @property User $user
 */
class ShopOrder extends superModel {

	public static $WAIT_PAY = 0;
	public static $ALRRADY_PAY = 1;

	/**
	 * @inheritdoc
	 */
	public static function tableName() {
		return 'shop_order';
	}

	public static function getCTableName() {
		return 'shop_order';
	}

	/**
	 * @inheritdoc
	 */
	public function rules() {
		return [
//            [['userId'], 'required'],
				[['userId', 'addressId', 'status', 'expressId'], 'integer'],
				[['amount'], 'number'],
				[['createtime', 'updatetime'], 'safe'],
				[['expressno'], 'string', 'max' => 50],
				[['addressId'], 'exist', 'skipOnError' => true, 'targetClass' => Address::className(), 'targetAttribute' => ['addressId' => 'addressId']],
				[['userId'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['userId' => 'id']],
		];
	}

	/**
	 * @inheritdoc
	 */
	public function attributeLabels() {
		return [
			'orderId' => 'ID',
			'userId' => '用户',
			'addressId' => '收获地址',
			'amount' => '订单总价',
			'status' => '订单状态',
			'expressId' => '快递方式',
			'expressno' => '快递单号',
			'createtime' => '创建时间',
			'updatetime' => '修改时间',
		];
	}

	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getOrderDetails() {
		return $this->hasMany(OrderDetail::className(), ['orderId' => 'orderId']);
	}

	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getAddress() {
		return $this->hasOne(Address::className(), ['addressId' => 'addressId']);
	}

	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getUser() {
		return $this->hasOne(User::className(), ['id' => 'userId']);
	}

	public function beforeSave($insert) {
		if (parent::beforeSave($insert)) {
			if ($this->isNewRecord) {
				$this->createtime = $this->getDateTime();
			} $this->updatetime = $this->getDateTime();
			return TRUE;
		} else {
			return FALSE;
		}
	}

}
